#include <stdbool.h>
#include <string.h>
#include <sharp-glob.h>

/*
typedef char * sharp_glob;
*/

sharp_glob sharp_glob_compile(char *expr_string){
    return expr_string;
}

bool sharp_glob_match(sharp_glob expr, char *target){
    if(expr == target)/* if this is the same expression, or both are NULL */
        return true;
    if(!expr || !target)
        return false;
    while(true){
        switch(expr[0]){
            case '\0':
                return (target[0]) ? false : true;
                break;
            case '?':
                if(!target[0])
                    return false;
                break;
            case '*':
                expr++;
                if(!expr[0])
                    return true;
                while(target[0]){
                    if(sharp_glob_match(expr, target))
                        return true;
                    target++;
                }
                break;
            default:
                if(expr[0] != target[0])
                    return false;
                break;
        }
        expr++;
        target++;
    }
    return true;
}

static bool globPartialMatch(sharp_glob expr, char *target){
    if(expr == target)
        return true;
    if(!expr || !target)
        return false;
    while(true){
        switch(expr[0]){
            case '\0':
                return true;
                break;
            case '?':
                if(!target[0])
                    return false;
                break;
            case '*':
                expr++;
                if(!expr[0])
                    return true;
                while(target[0]){
                    if(globPartialMatch(expr, target))
                        return true;
                    target++;
                }
                break;
            default:
                if(expr[0] != target[0])
                    return false;
                break;
        }
        expr++;
        target++;
    }
    return true;
}

char *sharp_glob_find(sharp_glob expr, char *target){
    if(!target)
        return NULL;
    if(!expr)
        return target;
    while(target[0]){
        if(globPartialMatch(expr, target))
            return target;
        target++;
    }
    return NULL;
}